package com.qxzl.Controller;

import com.alibaba.fastjson.JSON;
import com.qxzl.model.Clients;
import com.qxzl.model.Properties;
import com.qxzl.model.Services;
import com.qxzl.util.FindBeanByIp;
import com.qxzl.util.FunctionUtil;
import com.qxzl.util.Json;
import com.qxzl.util.StaticData;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.List;

import javax.annotation.Resource;

@Controller
@RequestMapping("QequestController")
public class QequestController {
    @Autowired
    private Properties properties;

    @Resource
    FindBeanByIp findBeanByIp;

    /**
     * 添加服务端
     *
     * @param services
     */
    @RequestMapping("/addService")
    @ResponseBody
    public String addService(Services services) {
        Json json = new Json();
        StaticData.services.add(services);
        json.setSuccess(true);
        json.setObj("添加服务端" + JSON.toJSONString(services));

        List<Services> servicesList = FunctionUtil.coveServicesJson(properties.getPach() + properties.getJsonServiceName());
        servicesList.add(services);
        FunctionUtil.writeJson(properties.getPach() + properties.getJsonServiceName(), JSON.toJSONString(servicesList));

        return json.toString();
    }

    /**
     * 添加客服端
     *
     * @param clients
     */
    @RequestMapping("/addClient")
    @ResponseBody
    public String addClient(Clients clients) {
        Json json = new Json();
        StaticData.clients.add(clients);
        json.setSuccess(true);
        json.setObj("添加客户端" + JSON.toJSONString(clients));
        List<Clients> clientsList = FunctionUtil.coveClientsJson(properties.getPach() + properties.getJsonClientsName());
        clientsList.add(clients);
        FunctionUtil.writeJson(properties.getPach() + properties.getJsonClientsName(), JSON.toJSONString(clientsList));

        return json.toString();

    }

    /**
     * 删除服务端
     *
     * @param services
     */
    @RequestMapping("/deleteService")
    @ResponseBody
    public String deleteService(Services services) {

        Json json = new Json();
        FunctionUtil.deleteService(services.getIp());
        json.setSuccess(true);
        json.setObj("删除服务端" + JSON.toJSONString(services));
        FunctionUtil.writeJson(properties.getPach() + properties.getJsonServiceName(), JSON.toJSONString(StaticData.services));
        return json.toString();

    }

    /**
     * 删除客户端
     *
     * @param clients
     */
    @RequestMapping("/deleteClient")
    @ResponseBody
    public String deleteClient(Clients clients) {
        Json json = new Json();
        FunctionUtil.deleteClient(clients.getIp());
        json.setSuccess(true);
        json.setObj("删除客户端" + JSON.toJSONString(clients));
        FunctionUtil.writeJson(properties.getPach() + properties.getJsonClientsName(), JSON.toJSONString(StaticData.clients));
        return json.toString();
    }

    /**
     * 修改请求
     */
    @RequestMapping("/updateRequest")
    @ResponseBody
    public String updateRequest(String Serviceip, String Clientsip) {
        Clients clients = findBeanByIp.getClientById(Clientsip);
        Services services = findBeanByIp.getServiceById(Serviceip);
        clients.setServices(services);

        FunctionUtil.writeJson(properties.getPach() + properties.getJsonClientsName(), JSON.toJSONString(StaticData.clients));
        Json json = new Json();
        json.setSuccess(true);
        json.setObj("修改请求");
        creatNginxConfigFile();
        return json.toString();
    }

    /**
     * 删除请求
     *
     * @param clients
     */
    @RequestMapping(value = "deleteRequest", produces = "text/json;charset=UTF-8")
    @ResponseBody
    public String deleteRequest(Clients clients) {
        Clients client = findBeanByIp.getClientById(clients.getIp());
        client.setServices(null);
        FunctionUtil.writeJson(properties.getPach() + properties.getJsonClientsName(), JSON.toJSONString(StaticData.clients));
        Json json = new Json();
        json.setSuccess(true);
        json.setObj("解绑请求" + JSON.toJSONString(clients));
        creatNginxConfigFile();
        return json.toString();
    }

    /**
     * 生成nginx配置文件
     */
    void creatNginxConfigFile(){
        try {
            File template =
                    new File("/root/devtools/nginx.conf.template");
            File replaceTemplate =
                    new File("/root/devtools/nginx.conf.replace.template");

            String  templateStr  = file2String(template);
            String  replaceTemplateStr  = file2String(replaceTemplate);



            String replaceStr = "";
            for (int i = 0; i < StaticData.clients.size(); i++) {
                Clients clients =  StaticData.clients.get(i);
                if (clients.getServices()!=null&&clients.getServices().getIp()!=null&&clients.getServices().getPort()!=null){
                  replaceStr +=
                          replaceTemplateStr.replaceAll("#clentip#", clients.getIp()).
                                  replaceAll("#serviceip#",clients.getServices().getIp()).
                                  replaceAll("#serviceport#",clients.getServices().getPort());
                }
            }
            if (replaceStr!=null){
                templateStr = templateStr.replace("#replace#",replaceStr);
            }

            File configFile = new File("/etc/nginx/nginx.conf");
            configFile.delete();
            FileOutputStream fos = null;
            fos = new FileOutputStream(configFile, false);
            OutputStreamWriter osw=new OutputStreamWriter(fos,"utf-8");
            osw.write(templateStr);
            osw.close();
            System.out.println("=======================");
            execCMD("nginx -s reload", ShellType.command);
        }catch (Exception e){
            e.printStackTrace();
        }

    }





    public String file2String(File file) throws Exception {

            System.out.println(file.exists());
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            fis.close();
            return new String(baos.toByteArray(), "utf-8");

    }



    /**
     * redis清除缓存
     *
     * @return
     */
    @RequestMapping(value = "redisBufferClear", produces = "text/json;charset=UTF-8")
    @ResponseBody
    public String redisBufferClear() {
        String result = "shell显示内容";
        String redisShellPath = "/root/devtools/redis.sh";
        try {
            result = execCMD(redisShellPath, ShellType.script);
        } catch (Exception e) {
        }
        Json json = new Json();
        json.setSuccess(true);
        json.setObj(result);
        return json.toString();
    }

    public enum ShellType {
        command, script
    }

    /**
     * Java执行shell
     *
     * @param shell
     * @param type  1 表示sh脚本文件, !=1表示具体命令
     * @return
     * @throws IOException
     */
    public static String execCMD(String shell, ShellType type) throws IOException {
        try {
            shell = (type == ShellType.command) ? shell : ("sh " + shell);
            String[] cmds = {"/bin/sh", "-c", shell};
            Process pro = Runtime.getRuntime().exec(cmds);
            pro.waitFor();
            InputStream in = pro.getInputStream();
            BufferedReader read = new BufferedReader(new InputStreamReader(in));
            String line = null;
            StringBuilder builder = new StringBuilder();
            while ((line = read.readLine()) != null) {
                builder.append(line);
            }
            String resultMsg = builder.toString();
            return (resultMsg == null || resultMsg.length() == 0) ? "未获取输出信息" : resultMsg;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "未获取输出信息";
    }

}